package com.ruoyi;
import com.coupang.openapi.sdk.Hmac;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * Coupang 退货地列表查询测试类
 * 参考文档：https://developers.coupangcorp.com/hc/zh-cn/articles/360033644814-退货地列表查询
 */
public class ReturnCenterList {

    private static final String HOST = "api-gateway.coupang.com";
    private static final int PORT = 443;
    private static final String SCHEMA = "https";
    
    //replace with your own accessKey
    private static final String ACCESS_KEY = "fe8a5ff1-28be-4a36-8694-577cc7960166";
    //replace with your own secretKey
    private static final String SECRET_KEY = "f05224e25ebb0c237564da5cce5be106926c7930";

    public void getReturnCenters() {
        //params
        String method = "GET";
        String vendorId = "A158000DM0";
        // 退货地列表查询 API 路径
        // 经过测试确认：v4 版本返回404（API不存在），必须使用 v1 版本
        String path = "/v2/providers/openapi/apis/api/v5/vendors/" + vendorId + "/returnShippingCenters";

        CloseableHttpClient client = null;
        try {
            //create client
            client = HttpClients.createDefault();
            
            //build uri - 按照官方示例：先构建 URIBuilder（只设置 path 和参数）
            URIBuilder uriBuilder = new URIBuilder()
                    .setPath(path)
//                    .addParameter("pageNum", "1")

//                    .addParameter("pageSize", "50")
                    ;

            /********************************************************/
            //authorize, demonstrate how to generate hmac signature here
            // 按照官方示例：查询参数参与签名
            String authorization = Hmac.generate(method, uriBuilder.build().toString(), SECRET_KEY, ACCESS_KEY);
            System.out.println("Authorization: " + authorization);
            System.out.println("Method: " + method);
            System.out.println("Path for signature: " + uriBuilder.build().toString());
            /********************************************************/
            
            // 然后再设置 scheme、host、port
            uriBuilder.setScheme(SCHEMA).setHost(HOST).setPort(PORT);
            
            HttpGet requestGet = new HttpGet(uriBuilder.build().toString());

            /********************************************************/
            // set headers - 按照官方示例设置请求头
            // set headers
            requestGet.addHeader("Authorization", authorization);
            requestGet.addHeader("X-Requested-By", vendorId);
//            /********************************************************/
            requestGet.addHeader("Content-Type", "application/json");
            requestGet.addHeader("X-EXTENDED-TIMEOUT", "90000");

            /********************************************************/
            
            System.out.println("\n请求头信息:");
            System.out.println("Authorization: " + authorization);
            System.out.println("X-Requested-By: " + vendorId);
            System.out.println("Content-Type: application/json");
            System.out.println("请求 URL: " + uriBuilder.build().toString());
            
            CloseableHttpResponse response = null;
            try {
                //execute get request
                System.out.println("\n发送退货地列表查询请求...");
                response = client.execute(requestGet);
                //print result
                System.out.println("\n=== 响应结果 ===");
                System.out.println("status code: " + response.getStatusLine().getStatusCode());
                System.out.println("status message: " + response.getStatusLine().getReasonPhrase());
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println("result: " + result);
                
                // 如果成功，解析并显示退货地信息
                if (response.getStatusLine().getStatusCode() == 200) {
                    System.out.println("\n=== 退货地信息解析 ===");
                    parseReturnCenters(result);
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    /**
     * 解析退货地列表数据（简单解析，实际项目中建议使用 JSON 解析库）
     */
    private void parseReturnCenters(String jsonResult) {
        System.out.println("退货地列表数据已获取，包含以下信息：");
        System.out.println("- returnCenterCode: 退货中心代码");
        System.out.println("- returnCenterName: 退货中心名称");
        System.out.println("- address: 地址信息");
        System.out.println("- contactNumber: 联系电话");
        System.out.println("- 其他详细信息...");
        System.out.println("\n请从返回的 JSON 数据中复制 returnCenterCode 用于商品注册。");
    }

    public static void main(String[] args) {
        System.out.println("========================================");
        System.out.println("Coupang 退货地列表查询 API 测试");
        System.out.println("========================================\n");
        
        ReturnCenterList returnCenterList = new ReturnCenterList();
        returnCenterList.getReturnCenters();
        
        System.out.println("\n========================================");
        System.out.println("测试完成");
        System.out.println("========================================");
        
        System.out.println("\n使用说明：");
        System.out.println("1. 如果查询成功，会返回您账号下所有可用的退货地列表");
        System.out.println("2. 从返回结果中找到 returnCenterCode（退货中心代码）");
        System.out.println("3. 将找到的代码替换到 ProductRegistration.java 中");
        System.out.println("4. 然后重新运行商品注册测试");
    }
}
